package cn.scnu.service.impl;

import cn.hutool.core.io.resource.ResourceUtil;
import cn.scnu.common.util.GisUtil;
import cn.scnu.mapper.Clipgeometry2Mapper;
import cn.scnu.model.dto.BaiYunRegionAttrDTO;
import cn.scnu.model.dto.RegionCountDTO;
import cn.scnu.model.entity.Clipgeometry2;
import cn.scnu.service.IClipgeometry2Service;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author hqzqaq
 * @since 2024-11-25
 */
@Service
@DS("master_3")
@RequiredArgsConstructor
@Slf4j
public class Clipgeometry2ServiceImpl extends ServiceImpl<Clipgeometry2Mapper, Clipgeometry2> implements IClipgeometry2Service {
    private final Clipgeometry2Mapper mapper;

    @Value("${shp.path}")
    private String shpPath;

    @Value("${shp.charsetName}")
    private String charsetName;

    @SneakyThrows
    @Override
    public List<RegionCountDTO> getRegionCount() {
        // 读取resources下的baiyun文件夹下的白云shp，获取每一个feature的wkt
        List<BaiYunRegionAttrDTO> attrFromShp = GisUtil.getAttrFromGeoJson(ResourceUtil.getStream(shpPath), BaiYunRegionAttrDTO.class);
        // 遍历每一个feature的wkt，查询数据库中是否有对应的region
        return attrFromShp.stream().map(attr -> {
            String wkt = attr.getGeometry();
            Integer count = mapper.getRegionCount(wkt);
            RegionCountDTO regionCountDTO = new RegionCountDTO();
            regionCountDTO.setRegionId(attr.getTownCode());
            log.info("regionName: {}, regionId: {}, count: {}", attr.getTownFullName(), attr.getTownCode(), count);
            regionCountDTO.setCount(count);
            return regionCountDTO;
        }).collect(Collectors.toList());
    }

    @Override
    public List<String> getUUIDForWkt(String wkt) {
        return mapper.getUUIDForWkt(wkt);
    }

    @Override
    public String getWktForUUID(String uuid) {
        return mapper.getWktForUUID(uuid);
    }
}
